import React from 'react';
import { router } from 'dva';
import { EnvConfig } from 'Configs';
import { Common } from 'UtilsCommon';
import aopc from 'aopc';
import layouts from './layouts';

const getPageLayoutCompoent = (list) => {
  const path = [];

  let listPage;
  let detailPage;
  list.forEach(p => {
    if (p.pageTemplateName === 'EntityPageList') listPage = p;
    else detailPage = p;
    path.push(p.path);
  });

  if (listPage && detailPage) {
    return {
      id: Common.createGuid(),
      path,
      component: layouts[listPage.pageLayoutTemplate](listPage, detailPage)
    };
  }
  return list[0];
};

const setLayoutPages = (pageList) => {
  aopc.componentPages = {};
  const obj = {};
  const list = [];
  pageList.forEach(p => {
    if (p.pageLayoutName === 'ComponentPage') aopc.componentPages[p.id] = p;
    else if (p.pageLayoutName && p.pageLayoutTemplate) {
      const ns = p.pageLayoutName.split(',');
      ns.forEach(n => {
        obj[n] = obj[n] || [];
        obj[n].push(p);
      });
    }
    else list.push(p);
  });

  for (const key in obj) {
    list.push(getPageLayoutCompoent(obj[key]));
  }

  return list;
};

const pages = setLayoutPages(aopc.getPages());

const { Router, Route, Switch } = router;
const wetRootPath = EnvConfig.getServiceUrl('WebRootPath')();

const getPath = (path) => (wetRootPath + path);

const renderRoute = (p, app) => {
  let path;
  if (typeof (p.path) === 'string') path = getPath(p.path);
  else path = p.path.map(m => getPath(m));

  return <Route path={path} key={p.id} exact component={(props) => React.createElement(p.component, { ...props, app, key: window.location.href })} />;
};

function RouterConfig({ history, app }) {
  return (
    <Router history={history}>
      <Switch>
        {pages.map(m => renderRoute(m, app))}
      </Switch>
    </Router>
  );
}

export default RouterConfig;
